

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.eclipse.persistence.jpa.JpaEntityManager;
import org.eclipse.persistence.sessions.UnitOfWork;
import org.eclipse.persistence.sessions.server.ServerSession;


public class Main {

	private static final String PERSISTENCE_UNIT_NAME = "jpatest";
	private final EntityManagerFactory entityManagerFactory;
	private final EntityManager entityManager;
	private final JpaEntityManager jpa;
	private final ServerSession serverSession;

	public Main() {
		// initializations
		entityManagerFactory = Persistence
				.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
		entityManager = entityManagerFactory.createEntityManager();
		jpa = (JpaEntityManager) entityManager.getDelegate();
		serverSession = jpa.getServerSession();
	}

	public void start() {
		// create 2 new users
		User john = new User();
		john.setName("John Doe");
		john.setAge(77);
		User oldUser = new User();
		oldUser.setName("oldUser");
		oldUser.setAge(50);
		User she = new User();
		she.setName("she");
		she.setAge(25);

		entityManager.getTransaction().begin();
		entityManager.persist(john);
		entityManager.persist(she);
		entityManager.persist(oldUser);
		entityManager.getTransaction().commit();

		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		oldUser.setName("newUserrrrrrrrrrrrr");
		oldUser.setAge(20);

		entityManager.getTransaction().begin();
		entityManager.merge(oldUser);
		entityManager.getTransaction().commit();

		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		entityManager.getTransaction().begin();
		entityManager.remove(she);
		entityManager.getTransaction().commit();

		for (int i = 1; i <= 3; i++) {
			User u = entityManager.find(User.class, i);
			if (u != null) {
				System.out.println("USER: " + u.getName() + " ID: " + u.getId()
						+ " AGE: " + u.getAge());
			}
		}

	}

	public UnitOfWork acquireUnitOfWork() {
		return serverSession.acquireClientSession().acquireUnitOfWork();
	}

	public static void main(String[] args) {
		Main main = new Main();
		main.start();
	}
}
